package han.cirno.corrupt.components.calendar

import han.cirno.corrupt.components.school.SchoolImpl
import org.jetbrains.annotations.Range
import java.util.Calendar

object CalendarUtil {
    fun findMondayOfWeekInYearTimeInMillis(year:Int, month:Int, dayOfMonth:Int):Long{
        val instance = Calendar.getInstance()
        instance.set(year,month-1,dayOfMonth)
        val dow = instance[Calendar.DAY_OF_WEEK]
        val delta=when(dow){
            Calendar.SUNDAY->-6
            Calendar.SATURDAY->-5
            Calendar.FRIDAY->-4
            Calendar.THURSDAY->-3
            Calendar.WEDNESDAY->-2
            Calendar.TUESDAY->-1
            Calendar.MONDAY->0
            else->0
        }
        instance.add(Calendar.DATE,delta)
        instance.set(Calendar.HOUR_OF_DAY,0)
        instance.set(Calendar.MINUTE,0)
        instance.set(Calendar.SECOND,0)
        instance.set(Calendar.MILLISECOND,0)
        return instance.timeInMillis
    }

    fun calcCurrentWeeks(firstDayTimeInMillis:Long, now:Calendar):@Range(from = 0L, to = 19L) Int{
        val msDelta = (now.timeInMillis - firstDayTimeInMillis).toFloat()
        return (msDelta / 1000f / 60f / 60f / 24f / 7f).toInt()
    }

    fun fromClassTimesToSeconds(time:Int):Pair<Long,Long>{
        val impl = SchoolImpl.impl?:return Pair(0,0)
        val classTime = impl.getClassTime()
        val (fromSecond,toSecond) = classTime.getTime(time)
        return Pair(fromSecond,toSecond)
    }

    fun getSeconds(h:Int,m:Int):Long{
        return h*60L*60L+m* 60L
    }

    fun getHourAndMinute(second:Long):Pair<Int,Int>{
        val hour=second/60/60
        val minute=(second-hour*60*60)/60
        return Pair(hour.toInt(),minute.toInt())
    }

    fun getDayHourMinuteAndSecond(millisecond:Long):Array<Int>{
        val day=millisecond/(1000*60*60*24)
        val hour=(millisecond%(1000*60*60*24))/(1000*60*60)
        val min=(millisecond%(1000*60*60))/(1000*60)
        val second=(millisecond%(1000*60))/1000
        return arrayOf(day.toInt(),hour.toInt(),min.toInt(),second.toInt())
    }
}